<!--
 * 组织/部门 抽屉
 *
 * @author tqfeiyang
 * @since 2024-09-19
-->
<template>
  <a-modal v-model:open="visible" :title="formState.departmentId ? '编辑部门' : '添加部门'" @ok="onSubmit" destroyOnClose>
    <a-form ref="formRef" :model="formState" :rules="formRules" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="上级id" name="parentId" v-if="formState.parentId != 0">
            <DepartmentTreeSelect ref="departmentTreeSelect" v-model:value="formState.parentId" :exclude-id="formState.departmentId" width="100%" />
        </a-form-item>
        <a-form-item label="名称" name="name">
            <a-input v-model:value="formState.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="排序" name="sort">
            <a-input v-model:value="formState.sort" placeholder="请输入排序" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
            <a-input v-model:value="formState.remark" placeholder="请输入备注" />
        </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
  import { reactive, ref, nextTick } from 'vue';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { departmentApi } from '/@/api/business/organization/department-api';
  import DepartmentTreeSelect from './department-tree-select.vue';

  // ---------------- 对外暴漏 --------------------

  defineExpose({ showModal });

  const emits = defineEmits(['refresh']);


  // ---------------- 显示/关闭 -------------------

  const visible = ref(false);

  function showModal(data) {
    Object.assign(formState, defaultFormState);

    if (data) {
      Object.assign(formState, data);
    }

    visible.value = true;

    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function closeModal() {
    visible.value = false;
  }


  // -------------------- 表单 --------------------

  const formRef = ref();

  const departmentTreeSelect = ref();

  const defaultFormState = {
    departmentId: undefined, //部门id
    parentId: undefined, //上级id
    name: undefined, //名称
    sort: undefined, //排序
    remark: undefined, //备注
  }

  const formState = reactive({ ...defaultFormState });

  const formRules = {
        parentId: [{ required: true, message: '上级部门不能为空' }],
        name: [
          { required: true, message: '部门名称不能为空' },
          { max: 50, message: '部门名称不能大于20个字符', trigger: 'blur' },
        ],
  };

  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      if (formState.departmentId) {
        updateDepartment();
      } else {
        createDepartment();
      }
    } catch (err) {
      console.log(err)
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  async function createDepartment() {
    try {
      SmartLoading.show();
      await departmentApi.createDepartment(formState);
      emits('refresh');
      closeModal();
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      SmartLoading.hide();
    }
  }

  async function updateDepartment() {
    if (formState.parentId == formState.departmentId) {
      message.warning('上级菜单不能为自己');
      return;
    }
    try {
      SmartLoading.show();
      await departmentApi.updateDepartment(formState.departmentId, formState);
      emits('refresh');
      closeModal();
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      SmartLoading.hide();
    }
  }

</script>

<style lang="less" scoped>
</style>
